package com.cabal.common.util.baidu;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;

import java.io.InputStream;
import java.net.URL;

@Slf4j
public class IP138Util {


	/**
	 * 取得本机的外网IP
	 * 
	 * @return
	 */
	public static String getExternalIp () {
		String ip = null;
		// 取得本机外网ip
		try (InputStream input = new URL("http://www.ip138.com/ip2city.asp").openStream()){
			String ipAddress = IOUtils.toString(input);
			ip = ipAddress.substring(ipAddress.indexOf('[') + 1, ipAddress.lastIndexOf(']'));
		} catch (Exception ex) {
			log.error("Get external ip", ex);
		}
		return ip;
	}
	
	public static String getIPAddress(String ip) {
		String address = null;
		// 取得本机外网ip
		try (InputStream input = new URL("http://www.ip138.com/ips138.asp").openStream()){
			String result = IOUtils.toString(input);
			address = result.substring(result.indexOf('[') + 1, result.lastIndexOf(']'));
		} catch (Exception ex) {
			log.error("Get ip address", ex);
		}
		return address;
	}
}
